<template>
  <div class="data-page">
    <div class="actions-card">
      <h2 class="title">数据管理</h2>
      <p class="subtitle">导入 / 导出 / 重置 本地存储数据</p>
      <div class="card-grid">
        <div class="action-card import" @click="triggerSelectFile">
          <div class="card-icon">
            <el-icon :size="56">
              <UploadFilled />
            </el-icon>
          </div>
          <h3 class="card-title">导入 JSON</h3>
          <p class="card-desc">选择 JSON 文件并覆盖本地存储数据</p>
        </div>

        <div class="action-card export" @click="exportJson">
          <div class="card-icon">
            <el-icon :size="56">
              <Download />
            </el-icon>
          </div>
          <h3 class="card-title">导出 JSON</h3>
          <p class="card-desc">导出当前本地存储的所有键值对</p>
        </div>

        <!-- <div class="action-card export-excel" @click="exportExcel">
          <div class="card-icon">
            <el-icon :size="56">
              <Document />
            </el-icon>
          </div>
          <h3 class="card-title">导出 Excel</h3>
          <p class="card-desc">导出弟子积分卡Excel表格</p>
        </div> -->
        <el-popconfirm title="请问当前的积分周期是？" width="300">
          <template #reference>
            <div class="action-card export-excel" >
              <div class="card-icon">
                <el-icon :size="56">
                  <Document />
                </el-icon>
              </div>
              <h3 class="card-title">导出 Excel</h3>
              <p class="card-desc">导出弟子积分卡Excel表格</p>
            </div>
          </template>
          <template #actions="{ confirm, cancel }">
            <el-button size="small" @click="exportExcel(0)">5月 ~ 10月</el-button>
            <el-button size="small" @click="exportExcel(1)">11月 ~ 次年4月</el-button>
            <el-button size="small" @click="cancel">取消</el-button>
          </template>
        </el-popconfirm>

        <div class="action-card reset" @click="resetAll">
          <div class="card-icon">
            <el-icon :size="56">
              <RefreshLeft />
            </el-icon>
          </div>
          <h3 class="card-title">重置数据</h3>
          <p class="card-desc">清空回收站并重置弟子积分记录</p>
        </div>
      </div>
    </div>
    <input ref="fileInputRef" type="file" accept="application/json" class="hidden-input" @change="onFileChange" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { UploadFilled, Download, RefreshLeft, Document } from '@element-plus/icons-vue';
import { DataService } from '@/service/DataService';
import { ExcelExportUtil } from '@/utils/ExcelExportUtil';
import { ScoringPeriodService } from '@/service/ScoringPeriodService';

const fileInputRef = ref<HTMLInputElement | null>(null);

const triggerSelectFile = (): void => {
  fileInputRef.value?.click();
};

const onFileChange = async (e: Event): Promise<void> => {
  const input = e.target as HTMLInputElement;
  const file = input.files?.[0];
  if (!file) return;

  try {
    const text = await file.text();
    const json = JSON.parse(text);
    const res = DataService.importFromObject(json);
    if (res.success) {
      ElMessage.success(res.message);
    } else {
      ElMessage.error(res.message);
    }
  } catch (err) {
    ElMessage.error('解析 JSON 失败');
  } finally {
    // 清空输入值以便连续选择相同文件也能触发 change
    if (input) input.value = '';
  }
};

const exportJson = (): void => {
  const obj = DataService.exportAllToObject(); // 获取所有数据
  const blob = new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json;charset=utf-8' }); // 创建 Blob 对象，Bolb 内容为格式化后的 JSON 字符串
  const url = URL.createObjectURL(blob); // 创建下载链接
  const a = document.createElement('a'); // 创建临时 <a> 元素
  const ts = new Date().toISOString().replace(/[:.]/g, '-'); // 时间戳，格式化为文件名友好形式
  a.href = url; // 设置下载链接
  a.download = `chengzheng-data-${ts}.json`; // 设置下载文件名
  document.body.appendChild(a); // 将 <a> 元素添加到 DOM
  a.click(); // 触发下载
  document.body.removeChild(a); // 移除临时 <a> 元素
  URL.revokeObjectURL(url); // 释放 URL 对象
  ElMessage.success('导出成功');
};

const exportExcel = async (period?: number | null): Promise<void> => {
  let currentPeriod = ScoringPeriodService.getCurrentPeriod();
  
  if (period !== null && period !== undefined) {
    currentPeriod = ScoringPeriodService.getPeriods(period);
  }
  console.log('当前积分周期:', currentPeriod, period);
  try {
    ElMessage.info('正在生成Excel文件，请稍候...');
    await ExcelExportUtil.exportToExcel(`诚正组弟子积分卡-${currentPeriod.name}-${new Date().toISOString().split('T')[0]}.xlsx`, currentPeriod);
    ElMessage.success('Excel导出成功');
  } catch (error) {
    console.error('导出Excel失败:', error);
    ElMessage.error('导出Excel失败，请稍后重试');
  }
};

const resetAll = async (): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      '此操作将清空回收站并重置弟子积分明细与规则分数，是否继续？',
      '确认重置',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    );
    const res = DataService.resetData();
    if (res.success) {
      ElMessage.success(res.message);
    } else {
      ElMessage.error(res.message);
    }
  } catch {
    // 用户取消
  }
};
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.data-page {
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  /* background: linear-gradient(120deg, #f9fbff 0%, #f6f7fd 100%); */
}

.actions-card {
  max-width: 960px;
  width: 100%;
  background: #ffffff;
  border-radius: 24px;
  padding: 48px;
  box-shadow: 0 18px 48px rgba(64, 158, 255, 0.15);
  text-align: center;
}

.title {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  color: #1f2d3d;
}

.subtitle {
  margin: 12px 0 40px;
  font-size: 16px;
  color: #909399;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 32px;
}

.action-card {
  position: relative;
  background: #f5f7fa;
  border-radius: 20px;
  padding: 32px 24px;
  transition: transform 0.25s ease, box-shadow 0.25s ease;
  cursor: pointer;
  overflow: hidden;
}

.action-card::after {
  content: '';
  position: absolute;
  inset: 0;
  opacity: 0;
  background: rgba(64, 158, 255, 0.08);
  transition: opacity 0.25s ease;
}

.action-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 16px 32px rgba(64, 158, 255, 0.18);
}

.action-card:hover::after {
  opacity: 1;
}

.action-card.import {
  background: linear-gradient(160deg, rgba(64, 158, 255, 0.18), rgba(64, 158, 255, 0.08));
}

.action-card.export {
  background: linear-gradient(160deg, rgba(103, 194, 58, 0.18), rgba(103, 194, 58, 0.08));
}

.action-card.export-excel {
  background: linear-gradient(160deg, rgba(255, 152, 0, 0.18), rgba(255, 152, 0, 0.08));
}

.action-card.reset {
  background: linear-gradient(160deg, rgba(245, 108, 108, 0.18), rgba(245, 108, 108, 0.08));
}

.card-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  margin-bottom: 24px;
}

.action-card.export .card-icon {
  color: #67c23a;
}

.action-card.export-excel .card-icon {
  color: #ff9800;
}

.action-card.reset .card-icon {
  color: #f56c6c;
}

.card-title {
  margin: 0 0 12px;
  font-size: 20px;
  font-weight: 600;
  color: #1f2d3d;
}

.card-desc {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.hidden-input {
  display: none;
}

@media (max-width: 768px) {
  .actions-card {
    padding: 32px 20px;
  }

  .card-grid {
    gap: 20px;
  }

  .card-icon {
    margin-bottom: 16px;
  }
}
</style>